{% extends "base.html" %}

{% block title %}工作负载 | 详情{% endblock %}

{% block head %}
  {{ super() }}
  <!-- DataTables -->
  <link rel="stylesheet" href="/static/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css">
{% endblock %}
<!-- bootstrap-select -->
<link rel="stylesheet" href="/static/css/bootstrap-select.min.css">


{% block content %}
  <!-- 页面头 -->
  <section class="content-header">
    <!--头部标题-->
    <h1>
      容器组（POD）
      <!--    <small>advanced tables</small>-->
    </h1>
    <!--面包屑-->
    <ol class="breadcrumb">
      <li><a href="/"><i class="fa fa-home"></i> 主页</a></li>
      <li><a href="/blues/blues/clusterler/cluster">集群管理</a></li>
      <li>工作负载</li>
      <li class="active">详请</li>
    </ol>
  </section>


  <!-- 页面内容 -->
  <section class="content">
    <div class="row">
      <div class="col-xs-12">
        <!--    顶部工具栏-->
        <form class="form-inline" style="margin-bottom: 10px">
          <div class="form-group">
            <label for="selectCluster"> <span style="color: red">*</span> 集群</label>
            <select class="form-control need-refresh-table" id="selectCluster" name="cluster_id" required>
              <option value="" selected>--请选择--</option>
            </select>
          </div>
          &nbsp;
          <div class="form-group">
            <label for="selectNamespace"> <span style="color: red">*</span> 命名空间</label>
            <select class="form-control need-refresh-table" id="selectNamespace" name="namespace" required>
              <!--            <option value="_all" selected>ALL</option>-->
            </select>
          </div>
          &nbsp;
        </form>

        <!--表格1-->
        <div class="box">
          <!--        <div class="box-header">-->
          <!--          <h3 class="box-title">节点概览</h3>-->
          <!--        </div>-->
          <div class="box-body">
            <table id="example1" class="table-hover table-bordered table-condensed table-striped"
                   style="width:100%;font-size: 90%">
              <thead>
              <tr>
                <th>Pod名称</th>
                <th>命名空间</th>
                <th>镜像</th>
                <!-- <th>主机</th> -->
                <th>状态</th>
                <!-- <th>原因</th> -->
                <th>重启次数</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
              </thead>
              <tbody id="tbody">
              </tbody>
            </table>
          </div>
          <!-- /.box-body -->
          <!-- Loading (remove the following to stop the loading)-->
          <div id="loading" class="overlay" style="display: block">
            <i class="fa fa-refresh fa-spin"></i>
          </div>
          <!-- end loading -->
        </div>
        <!-- /.box -->

      </div>
      <!-- /.col -->
    </div>
    <!-- /.row -->
  </section>
  <!-- /.页面内容 -->
{% endblock %}


{% block script %}
  <script src="/static/js/bootstrap-select.min.js"></script>
  <!-- DataTables -->
  <script src="/static/bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
  <script src="/static/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
  <!-- Page specific script -->
  <script type="text/javascript">
      // 定义全局变量
      var type = 'pods'
      // 解析URL
      var cluster_id = getQueryString("cluster_id")
      var namespace = getQueryString("namespace")
      var selector = getQueryString("selector")
      console.log(selector)

      // 检测本地是否保存变量
      if (cluster_id > 0) {
          console.log("save cluster_id to session_storage")
          sessionStorage.setItem("cluster_id", cluster_id)
      } else {
          cluster_id = sessionStorage.getItem("cluster_id")
          // 设置cluster_id默认值
          if (cluster_id == null) {
              cluster_id = 1
              sessionStorage.setItem("cluster_id", cluster_id)
          }
      }
      if (namespace) {
          sessionStorage.setItem("namespace", namespace)
      } else {
          namespace = sessionStorage.getItem("namespace")
          // 设置默认值
          if (namespace == null) {
              namespace = '_all'
              sessionStorage.setItem("namespace", namespace)
          }
      }


      // 页面载入完毕后执行接口调用
      $(document).ready(function () {
          //$('#loading').hide()
          // 获取所有集群列表，并填入下拉菜单
          $.get('/api/cluster_list', function (data) {
              var clusters = data
              console.log(data)
              for (let i in clusters) {
                  $('#selectCluster').append('<option value="' + clusters[i].id + '">' + clusters[i].name + '</option>')
              }
              // 如果url带cluster_id，则刷新namespace下拉菜单
              if (cluster_id > 0) {
                  $('#selectCluster').val(cluster_id)
                  refreshNamespace(cluster_id)
                  // 如果url带namespace，则刷新资源下拉菜单，刷新数据表格
                  if (namespace) {
                      $('#selectNamespace').val(namespace)
                      refreshTable(cluster_id, namespace, type)
                  }
              }
          })
      })


      function refreshTable(cluster_id, namespace, type) {
          $('#loading').show()
          // 数据有效性校验
          if (cluster_id === '' || namespace === '' || type === '') {
              bootbox.alert("有未填写的参数，请返回检查")
              return false
          }
          //接口调用，并填充数据Table

          let url = '/api/cluster/' + cluster_id + '/' + namespace + '/' + type + '/'
          if (selector) {
              url = '/api/v1/cluster/' + cluster_id + '/' + namespace + '/pods/?selector=' + selector
          }

          console.log(url)
          $.get(url, function (result) {
              console.log(result)
              $('#tbody').find('td').remove()

              // 不指定资源名查询，返回list
              for (let i in result.items) {
                  let pod = result.items[i].metadata.name
                  let ns = result.items[i].metadata.namespace
                  let container = result.items[i].spec.containers[0].name
                  let href_container = '/cluster/' + cluster_id + '/' + ns + '/containers/' + pod
                  let text = '<tr>'

                  // 添加pod名称信息
                  // text += `<td>${pod}</td>`

                  text += `<td><a href=${href_container}>${pod}</a></td>`


                  text += '<td>' + ns + '</td>'

                  // text += '<td>' + container + '</td>'

                  // 添加pod 镜像信息
                  text += '<td>'
                  // console.log(result.items[i].spec.containers.length)
                  for (let j = 0; j < result.items[i].spec.containers.length; j++) {
                      if (j == 0) {
                          text += result.items[i].spec.containers[j].image
                      } else {
                          text += '<br>' + result.items[i].spec.containers[j].image
                      }
                  }
                  text += '</td>'

                  // 添加pod 主机信息
                  //  text += '<td>' + result.items[i].spec.nodeName + '<br>' + result.items[i].status.hostIP + '</td>'

                  // 添加pod 状态和原因 信息
                  let status = ''
                  let reason = ''
                  if ('containerStatuses' in result.items[i].status && result.items[i].status.containerStatuses.length > 0) {
                      for (let x in result.items[i].status.containerStatuses[0].state) {
                          status += x
                          if (result.items[i].status.containerStatuses[0].state[x].reason) {
                              reason = result.items[i].status.containerStatuses[0].state[x].reason
                          }
                      }
                  }
                  text += '<td>' + status + '</td>'
                  //  text += '<td>' + reason + '</td>'
                  // text += '<td>' + JSON.stringify(result.items[i].metadata.labels) + '</td>'


                  //
                  let restart_num = 0
                  for (let k in result.items[i].status.containerStatuses) {
                      // console.log(result.items[i].status.containerStatuses[k].restartCount)
                      restart_num += Number(result.items[i].status.containerStatuses[k].restartCount)
                  }
                  text += '<td>' + restart_num + '</td>'
                  text += '<td>' + result.items[i].metadata.creationTimestamp + '</td>'

                  // 添加日志和命令行
                  let ws_url = '/cluster/logs/' + cluster_id + '/' + ns + '/' + pod + '/' + container
                  let exec_url = '/cluster/terminal/' + cluster_id + '/' + ns + '/' + pod + '/' + container

                  //text += '<td><a href="' + ws_url + '"><i class="fa fa-file-text-o"></i> </a>'
                  //text += '<a href="' + exec_url + '"><i class="glyphicon glyphicon-console"></i> </a>'
                  text += '<td><a href="' + ws_url + '">日志  </a>'
                  text += '<a href="' + exec_url + '">命令行 </a>'
                  text += '</td></tr>'

                  $('#tbody').append(text)
              }

              $('#example1').DataTable({
                  language: {
                      "url": "/static/language.json"
                  },
                  processing: true,
                  paging: true,
                  lengthChange: true,
                  searching: true,
                  ordering: true,
                  order: [[1, 'asc'], [0, 'asc']],
                  autoWidth: true,
                  responsive: true,
                  columnDefs: [{'width': '8%', "targets": 6}]
              });

              $('#loading').hide()
          })
      }

      function refreshNamespace(cluster_id) {
          console.log("refresh namespace");
          // var current_cluster_id = $('#selectCluster').val().trim()
          $("#selectNamespace").find('option').remove();
          $("#selectNamespace").append('<option value="_all">所有</option>');
          $.get('/api/v1/cluster/' + cluster_id + '/namespaces', function (data) {
              for (let i in data.items) {
                  $("#selectNamespace").append('<option value="' + data.items[i].metadata.name + '">' + data.items[i].metadata.name + '</option>');
              }
              if (namespace) {
                  $('#selectNamespace').val(namespace)
              }
          });
      }

      // 检测集群、命名空间，任一选择变化，则重载页面
      $(".need-refresh-table").change(function () {
          console.log("need-refresh-table")
          let cluster_id = $('#selectCluster').val()
          // var namespace = $("#selectNamespace").find("option:selected").text().trim()
          let namespace = $("#selectNamespace").val()

          console.log(cluster_id, namespace)

          if (cluster_id > 0) {
              let url = '/cluster/' + type + '/?cluster_id=' + cluster_id
              if (namespace) {
                  url += '&namespace=' + namespace
              } else {
                  url += '&namespace=_all'
                  $('#selectNamespace').val(namespace)
              }
              location.href = url
          }
      })


  </script>

{% endblock %}